package com.text.demmongodb.config;

import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @ClassName MongodbConfig
 * @Author By wen
 * @Description mongodb配置类
 * @Date 2023/10/30 16:36
 * @Version 1.0
 */
@Configuration
@EnableTransactionManagement
public class MongodbConfig {

    /**
     * 开启mongodb事务管理
     * @param mongoDatabaseFactory
     * @return
     */
    @Bean
    public MongoTransactionManager transactionManager(MongoDatabaseFactory  mongoDatabaseFactory) {
        return new MongoTransactionManager(mongoDatabaseFactory);
    }

    /**
     * 此配置自动删除建立集合时默认创建的_class字段
     * @param mongoDatabaseFactory
     * @param mongoMappingContext
     * @return
     */
    @Bean(name = "mongoTemplate")
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory, MongoMappingContext mongoMappingContext) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        //去掉_class字段
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(mongoDatabaseFactory,mappingConverter);
    }

}
